package com.example.demo.filter;

import com.example.demo.enums.Status;
import com.example.demo.utill.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始了");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1=(HttpServletRequest)servletRequest;
        String uri=servletRequest1.getRequestURI();
        if(uri.startsWith("/cart")||uri.startsWith("/order")){
            HttpSession session=servletRequest1.getSession();
            Object userId=session.getAttribute("userId");
            ResponseResult res=new ResponseResult();
            if(userId==null){
                res.setCode(500);
                res.setStatus(Status.NO_LOGIN);
                res.setMessage("你还没有登录");

                //将对象转换为Json,并返回给前端
                String json=new ObjectMapper().writeValueAsString(res);
                HttpServletResponse servletResponse1=(HttpServletResponse)servletResponse;
                servletResponse1.setContentType("application/json;charset=utf8");
                servletResponse1.getWriter().write(json);
                return;
            }
        }
        //放行，不然会出现网页无法显示
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("过滤器被销毁了");
    }
}
